package com.peanut.baby.mvp.livedetail.group;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.model.BBSComment;
import com.peanut.baby.model.LiveGroupRel;
import com.peanut.baby.model.LiveMsg;
import com.peanut.baby.model.LiveRoom;
import com.peanut.baby.mvp.BaseMvpFragment;
import com.peanut.baby.mvp.bbs.detail.BBSCommentRecyclerAdapter;
import com.peanut.baby.mvp.bbs.detail.BBSMomentDetailActivity;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.expert.ExpertProfileActivity;
import com.peanut.baby.mvp.liveroom.AppVoicePlayer;
import com.peanut.baby.mvp.liveroom.LiveRoomActivity;
import com.peanut.baby.mvp.liveroom.LiveRoomMessageAdapter;
import com.peanut.baby.mvp.liveroom.RoomLectureFragment;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.qadetail.QADetailActivity;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.pullrecycle.BaseRecyclerAdapter;
import com.peanut.devlibrary.widget.pullrecycle.PullRecyclerView;
import com.peanut.devlibrary.widget.pullrecycle.layoutmanager.XLinearLayoutManager;
import com.tencent.mars.xlog.Log;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by anonymouslystudio on 2017/8/2.
 */

public class LiveDetailGroupFragment extends BaseMvpFragment implements BaseRecyclerAdapter.OnRecyclerItemClickListener, View.OnClickListener, LiveDetailGroupContract.View {
    @BindView(R.id.pull_recycler)
    PullRecyclerView pullRecycler;
    @BindView((R.id.enter_room))
    View enter_room;
    @BindView((R.id.copywx))
    View copywx;
    @BindView(R.id.addwxlayout)
    View addwxlayout;
    @BindView(R.id.input_container)
    View input_container;

    Unbinder unbinder;

    private String userId = "";
    private List<LiveRoom> comments;
    private LiveGroupRecyclerAdapter adapter;

    private LiveDetailGroupPresenter presenter;

    LiveRoom liveRoom;
    LiveRoom roomPlaying;

    private LiveRoomMessageAdapter.OnAudioPlayFinishedListener listener;

    public static LiveDetailGroupFragment newInstance(LiveRoom liveRoom) {
        LiveDetailGroupFragment fg = new LiveDetailGroupFragment();
        Bundle bundle = new Bundle();
        fg.setArguments(bundle);
        bundle.putSerializable("liveRoom", liveRoom);
        return fg;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_live_detail_group, null);
        unbinder = ButterKnife.bind(this, rootView);
        pullRecycler.enablePullRefresh(false);
        pullRecycler.enableLoadMore(false);
        enter_room.setOnClickListener(this);
        copywx.setOnClickListener(this);
        addwxlayout.setVisibility(View.VISIBLE);
//        pullRecycler.setOnRecyclerRefreshListener(this);
        return rootView;
    }

    @Override
    public void initData() {
        liveRoom = (LiveRoom) getArguments().getSerializable("liveRoom");
        presenter = new LiveDetailGroupPresenter(this, getActivity());
        comments = new ArrayList<>();
        if (liveRoom.group != null && liveRoom.group.size() > 0)
            comments.addAll(liveRoom.group);
        adapter = new LiveGroupRecyclerAdapter(getActivity(), comments);
//        pullRecycler.setLayoutManager(new XLinearLayoutManager(getActivity()));
        pullRecycler.setAdapter(adapter);
        adapter.setOnRecyclerItemClickListener(this);
//        presenter.getComments(userId,pageNo,pageSize);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onItemClick(View view, int position) {
        if (InitManager.getInstance().getUser() == null) {
            LoginActivity.startForResult(getActivity());
            return;
        }
        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
            BindMobileActivity.startForResult(getActivity());
            return;
        }

        LiveRoom room = comments.get(position);
        if (room.isEnroled == 1) {
            int playStatus = room.playStatus;
            if (playStatus == 1 && AppVoicePlayer.getInstance().isPlaying()) {
                AppVoicePlayer.getInstance().releasePlayer();
                roomPlaying = null;
                InitManager.getInstance().playingId = 0;
                room.playStatus = 0;
                adapter.notifyDataSetChanged();
            } else {
                for (LiveRoom room2 : comments) {
                    room2.playStatus = 0;
                }
                AppVoicePlayer.getInstance().releasePlayer();
                roomPlaying = room;
                room.playStatus = 1;
                adapter.notifyDataSetChanged();
                showProgress("获取播放列表...", false);
                presenter.messageListGet(comments.get(position).roomId + "");
            }
        } else {
            showProgress("正在报名,消耗" + room.consumePoint + "花生壳", false);
            presenter.joinRooms(room.roomId + "", room.consumePoint + "");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.enter_room:
                if (InitManager.getInstance().getUser() == null) {
                    LoginActivity.startForResult(getActivity());
                    return;
                }
                if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                    BindMobileActivity.startForResult(getActivity());
                    return;
                }
                String uid = InitManager.getInstance().getUserId();
                if (liveRoom.group == null || liveRoom.group.size() == 0) {
                    showToast("当前课程没有系列课");
                    return;
                }
                if (uid.equals(liveRoom.expertId)
                        || uid.equals(liveRoom.serverId)) {
                    LiveRoomActivity.start(getActivity(), liveRoom);
                } else {
                    boolean allEnrole = true;
                    boolean notAllEnrole = false;
                    List<LiveRoom> liveRooms = liveRoom.group;
                    int enrolePoint = 0;
                    List<String> roomIds = new ArrayList<>();
                    for (LiveRoom vr : liveRooms) {
                        if (vr.isEnroled == 0) {
                            allEnrole = false;
                            roomIds.add(vr.roomId + "");
                        }
                        if (vr.isEnroled == 1) {
                            enrolePoint = enrolePoint + Integer.parseInt(vr.consumePoint);
                            notAllEnrole = true;
                        }
                    }

                    if (allEnrole) {//播放
                        showProgress("获取播放列表...", false);
                        LiveRoom room = comments.get(0);
                        roomPlaying = room;
                        room.playStatus = 1;
                        adapter.notifyDataSetChanged();
                        presenter.messageListGet(comments.get(0).roomId + "");
                    } else {//报名
                        int needPoint = 0;
                        String str = StringUtils.join(roomIds.toArray(), ",");
                        if (!notAllEnrole) {
                            needPoint = liveRoom.liveGroup.consumePoint;
                        } else {
                            needPoint = liveRoom.liveGroup.consumePoint - enrolePoint;
                        }
                        showProgress("正在报名,消耗" + needPoint + "花生壳", false);
                        presenter.joinRooms(str, needPoint + "");
                    }
                }
                break;
            case R.id.copywx:
                ClipboardManager clipboard = (ClipboardManager) this.getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText(null, "huashengkf");
                clipboard.setPrimaryClip(clipData);
                showToast("复制成功");
                break;
        }
    }

    @Override
    public void onRequestFailed(String code, String reason) {
        dismissProgress();
    }

    @Override
    public void onJoinSuccess(String roomIds) {
        dismissProgress();
        showToast("报名成功");
        if (roomIds.indexOf(",") > 0) {
            for (LiveRoom room : comments) {
                room.isEnroled = 1;
            }
        } else {
            for (LiveRoom room : comments) {
                if (String.valueOf(room.roomId).equals(roomIds)) {
                    room.isEnroled = 1;
                }
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onMessageListGet(List<LiveMsg> newMsgs) {
        dismissProgress();
        List<String> audioList = new ArrayList<>();
        if (newMsgs != null && newMsgs.size() > 0) {
            for (LiveMsg msg : newMsgs) {
                if (msg.messageType == 3)
                    audioList.add(msg.getMessageContent().url);
            }
        }
        if (audioList.size() > 0) {
            AppVoicePlayer.getInstance().playList(audioList, new AppVoicePlayer.OnAppVoicePlayListener() {
                @Override
                public void onException(String reason) {
                    Toast.makeText(getActivity(), "音频播放出错", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPlayFinished() {
                    if (roomPlaying != null) {
                        roomPlaying.playStatus = 0;
                        adapter.notifyDataSetChanged();
                    }
                }

                @Override
                public void onPlayStarted() {
                }

                @Override
                public void onInterrupt() {

                }

            });

        } else {
            Toast.makeText(getActivity(), "该直播没有音频", Toast.LENGTH_SHORT).show();
            if (roomPlaying != null) {
                roomPlaying.playStatus = 0;
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onLiveRoomsGet(List<LiveGroupRel> list) {

    }
}
